package handles

import (
	"github.com/gin-gonic/gin"
	"shao-mai/cache"
	"shao-mai/models"
	"shao-mai/pkg"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.User
	redis_key := "user_login" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount == 3 {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "密码错误超过3次需要限制登录2小时",
		})
		return
	}
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "不合法",
		})
		return
	}
	if user.ID == 0 {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "此用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
		if errCount == 2 {
			c.JSONP(200, gin.H{
				"code": 500,
				"msg":  "密码错误超过3次需要限制登录2小时",
			})
			return
		}
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "账号或密码错误",
		})
		return
	}
	c.JSONP(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return
}
func UserRoleAdd(c *gin.Context) {
	uid := c.PostForm("uid")
	rid := c.PostForm("rid")
	if uid == "" || rid == "" {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	var user models.User
	err := models.DB.Create(&user).Error
	if err != nil {
		c.JSONP(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSONP(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	id := c.Query("id")
	/*
		SELECT * FROM roles
		LEFT JOIN user_roles on user_roles.rid =roles.id
		WHERE user_roles.uid = 1
	*/
	var user models.Role
	models.DB.Table("roles").
		Joins("LEFT JOIN user_roles on user_roles.rid =roles.id").
		Where("user_roles.uid = ?", id).Debug().Find(&user)
	c.JSONP(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}
func UserNodeList(c *gin.Context) {
	id := c.Query("id")
	/*
		SELECT
		  *
		FROM
		  nodes
		  LEFT JOIN role_nodes on role_nodes.rid = nodes.id
		WHERE
		  role_nodes.rid = 1
	*/
	var user models.Node
	models.DB.
		Joins("LEFT JOIN role_nodes on role_nodes.rid = nodes.id").
		Where("role_nodes.rid = ?", id).
		Find(&user)
	c.JSONP(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
	return
}
